package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天器的服务端
 */

public class Server5 {
    private ServerSocket serverSocket;

    //v4:该集合用于保存所有客户端的输出流,用于广播消息
    private List<PrintWriter> allOut=new ArrayList<>();
    public Server5(){

        try {
            System.out.println("正在启动服务端");
            serverSocket=new ServerSocket(8088);System.out.println("服务端启动完毕！");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void start(){
        try {
            while (true){
                System.out.println("等待客户端连接");
                Socket socket=serverSocket.accept();//localhost表示本机IP
                System.out.println("一个客户端连接上了");
                ClientHandler handler=new ClientHandler(socket);
                Thread t=new Thread(handler);
                t.start();


            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server5 server=new Server5();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;//记录客户端ip地址

        public ClientHandler(Socket socket){
            this.socket=socket;
            //通过socket获取远端计算机的IP地址的字符串格式
            host=socket.getInetAddress().getHostAddress();
        }
        public void run(){
            //V5:提高pw的作用域,以便于finally中可以将其从allOut集合中删除
            PrintWriter pw=null;
            try {
                InputStream in= socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br=new BufferedReader(isr);

                //V3:通过socket获取输出流用于给客户端发送信息
                OutputStream out=socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw=new BufferedWriter(osw);
                pw=new PrintWriter(bw,true);

                //V5:多线程向集合中添加元素可能产生并发安全问题,因此必须同步执行
                synchronized (allOut){//通过同步监视器对象就选取临界资源
                //V4:将对应该客户端的输出流存入到共享集合allOut中,便于其他线程访问到
                allOut.add(pw);
                }
                //V5:广播消息,该客户端上线了
                sendMessage(host+"上线了,当前在线人数:"+allOut.size());

                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String message;
                while ((message=br.readLine())!=null){
                    //V5:读取到客户端消息广播时改为调用sendMessage方法
                    sendMessage(host+"说:"+message);
                }
            } catch (IOException e) {

                //V5:在finally中处理客户端断开的操作
            }finally {
                //V5:将该客户端的输出流从allOut集合中删除
                allOut.remove(pw);
                //广播客户端下线了
                sendMessage(host+"下线了,当前在线人数:"+allOut.size());

            }
        }

        private void sendMessage(String message){
            System.out.println(host+"说:"+message);
            //V4:遍历allOut集合,给所有客户端发送这个信息
            //V5:新循环就是迭代器,迭代器要求遍历过程不能用集合方法增删元素
            synchronized (allOut){
                for (PrintWriter o:allOut) {
                o.println(message);
                }
            }
        }
    }
}
